﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Common;
using Transcend.Utility;
using Transcend.FileUploader.Utility;
namespace Transcend.OnlineImageImp
{
    public partial class frmSelectBiz : Form
    {
        DbConnection _conn;
        decimal _userId;
        public DictionaryWraper Settings { get; set; }
        public frmSelectBiz(DbConnection conn, decimal userId)
        {
            _conn = conn;
            _userId = userId;
            InitializeComponent();
            gvBiz.AutoGenerateColumns = false;   //不允许自动生成列
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {

            string sqlString = "select b.bizid ,b.bizno,u.name UserName,n.stepname,n.createdate ReceiveTime,\n" +
            "b.curuserid from bizarchive b, wfnode n,csuser u where b.curuserid=u.userid and b.wfnodeid=n.wfnodeid\n" +
            "  and b.subtypeid=23100 and b.wfnodeid=15 and exists(select 1 from arcdat.csbusinesslogs l\n" +
            "   where l.bizid=b.bizid and l.compname='OnlineReceive')";
            sqlString = string.Format("With qry as ({0})\n", sqlString);

            string where = "";
            if (rbCurUser.Checked)
                where = string.Format("curuserid={0}", _userId);
            if (!string.IsNullOrEmpty(txtBizNo.Text.Trim()))
            {
                if (!string.IsNullOrEmpty(where)) where += " And ";
                where += string.Format(" BizNo='{0}'", txtBizNo.Text.Trim().Replace("'", "''"));
            }

            string sql = sqlString + " Select * From qry ";
            if (!string.IsNullOrEmpty(where)) sql += " where " + where;

            sql += " order by bizid desc";
            List<OnlineDataRow> rows = new List<OnlineDataRow>();  //所有数据行
            using (var cmd = _conn.CreateCommand())
            {
                cmd.CommandText = sql;
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var row = new OnlineDataRow();
                        row.BizId = System.Convert.ToDecimal(reader["BizId"]);   //业务序号 
                        row.BizNo = reader.IsDBNull(1) ? "" : reader.GetString(1);  //业务编号
                        row.UserName = reader.GetString(2);  //用户名称
                        row.StepName = reader.GetString(3);  //步骤名称
                        row.ReceiveTime = reader.GetDateTime(4);
                        rows.Add(row);
                    }
                }
            }
            gvBiz.DataSource = rows;
        }

        /// <summary>
        /// 下载文件、导出图像
        /// </summary>
        /// <param name="URL"></param>
        /// <param name="filename"></param>
        /// <param name="prog"></param>
        public void DownloadFile(string URL, string filename, System.Windows.Forms.ProgressBar prog)
        {
            try
            {
                System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
                long totalBytes = myrp.ContentLength;
                if (prog != null)
                {
                    prog.Maximum = (int)totalBytes;
                }
                System.IO.Stream st = myrp.GetResponseStream();
                System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
                long totalDownloadedByte = 0;
                byte[] by = new byte[1024];
                int osize = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    System.Windows.Forms.Application.DoEvents();
                    so.Write(by, 0, osize);
                    if (prog != null)
                    {
                        prog.Value = (int)totalDownloadedByte;
                    }
                    osize = st.Read(by, 0, (int)by.Length);
                }
                so.Close();
                st.Close();
            }
            catch (System.Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 下载业务文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDownload_Click(object sender, EventArgs e)
        {
            DialogResult = System.Windows.Forms.DialogResult.Cancel;
            if (gvBiz.SelectedRows.Count == 0)
            {
                MessageBox.Show("请选择一个业务后再导出。", "操作提示");
                return;
            }
            var row = gvBiz.SelectedRows[0].DataBoundItem as OnlineDataRow;

            string page = "page/AbilityCaller.aspx";
            string abilityName = "Transcend.Archive.Ability.DocExchange.ExportImage";
            string url = "", regionName = "";
            decimal fromBizId = 0;
            //查找在线导入时保存在日志里的信息
            string sql = string.Format("select logcontent from csbusinesslogs l where l.bizid={0} and compname={1} and logtype={2}",
                row.BizId, "'OnlineReceive'", 1);
            OnlineRegistInfo regInfo = null;
            using (var cmd = _conn.CreateCommand())
            {
                cmd.CommandText = sql;
                var strRegInfo = cmd.ExecuteScalar();
                if (DBNull.Value.Equals(regInfo))
                {
                    MessageBox.Show(string.Format("业务[{0}]缺少在经移交的注册信息，不能在线导入图像。", row.BizNo), "操作提示");
                    return;
                }
                regInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<OnlineRegistInfo>(strRegInfo.ToString());

                //根据来源区县，找出来源区县的接口地址
                sql = "Select d.exchangeurl,d.Name from division d where d.id=" + regInfo.FromDivisionId;
                cmd.CommandText = sql;
                using (var reader = cmd.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        var _excUrl = reader[0];
                        regionName = reader[1].ToString();
                        if (!DBNull.Value.Equals(_excUrl)) url = _excUrl.ToString();
                    }
                }
                fromBizId = regInfo.FromBizId;
            }

            if (string.IsNullOrEmpty(url))
            {
                MessageBox.Show(string.Format("业务[{0}]从[{1}]在线移交获得，而系统中没有定义[{1}]的移交接口地址，请联系管理员进行正确配置。", row.BizNo, regionName), "操作提示");
                return;
            }
            if (fromBizId == 00)
            {
                MessageBox.Show(string.Format("业务[{0}]从[{1}]在线移交获得，但原来的移交业务编号没有正确注册，不能进行再线图像获取。", row.BizNo, regionName), "操作提示");
                return;
            }
            if (!url.EndsWith("/")) url += "/";
            url += page;

            HttpItem pms = new HttpItem
            {
                Method = "POST",
                URL = url,
                Postdata = string.Format("bizid={0}&abilityName={1}", System.Convert.ToInt32(fromBizId), abilityName),
                ContentType = "application/x-www-form-urlencoded;charset=utf-8",
                Encoding = System.Text.Encoding.UTF8
            };
            HttpHelper helper = new HttpHelper();
            FolderBrowserDialog dlg = new FolderBrowserDialog();
            if (dlg.ShowDialog(this) != System.Windows.Forms.DialogResult.OK) return;
            string path = dlg.SelectedPath;   //下载文件存放路径
            dlg.Dispose();

            dlLabel.Text = "服务器正在准备下载内容...";
            Application.DoEvents();

            #region 开始下载
            var response = helper.DownloadFile(pms);
            var stream = response.GetResponseStream();
            if (!response.ContentType.Equals("application/octet-stream", StringComparison.OrdinalIgnoreCase))
            {
                //当前不是下载文件，返回的是错误信息
                using (var reader = new System.IO.StreamReader(stream))
                {
                    string html = reader.ReadToEnd();
                    stream.Dispose();
                    var result = Newtonsoft.Json.JsonConvert.DeserializeObject<EasyUIResultInfo<string>>(html);
                    if (!result.success)
                    {
                        MessageBox.Show(result.message, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    return;
                }

            }

            if (!path.EndsWith(@"\")) path += "\\";
            string fullName = path + row.BizNo + ".csdbf";
            System.IO.Stream fs = System.IO.File.Create(fullName);


            dlprogress.Maximum = System.Convert.ToInt32(response.ContentLength);
            dlLabel.Text = "正在下载...";

            long totalDownloadedByte = 0;
            byte[] by = new byte[1024];
            int osize = stream.Read(by, 0, (int)by.Length);
            while (osize > 0)
            {
                totalDownloadedByte = osize + totalDownloadedByte;
                System.Windows.Forms.Application.DoEvents();
                fs.Write(by, 0, osize);
                dlprogress.Value = (int)totalDownloadedByte;
                Application.DoEvents();
                osize = stream.Read(by, 0, (int)by.Length);
            }
            stream.Dispose();
            fs.Position = 0;
            #endregion
            dlLabel.Text = "正在解密文件包...";

            #region 文件解压
            var opt = new Ionic.Zip.ReadOptions();
            opt.Encoding = Encoding.GetEncoding("GB2312");

            dlprogress.Value = 0;
            Ionic.Zip.ZipFile zf = Ionic.Zip.ZipFile.Read(fs, opt);
            zf.Password = "123456";
            string startPath = path + row.BizNo;
            dlprogress.Maximum = zf.Entries.Count;
            zf.ExtractProgress += new EventHandler<Ionic.Zip.ExtractProgressEventArgs>(unzipProgress);
            zf.ExtractAll(startPath, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
            fs.Close();
            fs.Dispose();
            zf.Dispose();
            System.IO.File.Delete(fullName);   //删除文件
            #endregion
            dlLabel.Text = "文件解压完成，正在准备上传文件夹";
            dlprogress.Value = 0;
            List<FileRelation> fileRelations = new List<FileRelation>();
            using (var cmd = _conn.CreateCommand())
            {
                //sql = "Select d.FileId,d.FromPk From docFile d,bizDocFile b where d.fileId=b.fileId And b.bizid=" + row.BizId;

                sql = Settings.GetString("OnlineDirChangeName.Sql");
                cmd.CommandText = string.Format(sql, row.BizId);
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        FileRelation item = new FileRelation();
                        if (reader.IsDBNull(0) || reader.IsDBNull(1)) continue;
                        item.FileId = reader.GetValue(0).ToString();
                        item.FromFileId = reader.GetDecimal(1);
                        fileRelations.Add(item);
                    }
                    reader.Close();
                }
            }
            startPath = System.IO.Path.Combine(startPath, System.Convert.ToInt32(fromBizId).ToString());
            IOHelper.changeFileDir(startPath, fileRelations);
            dlLabel.Text = "处理完成。";
            if (MessageBox.Show(string.Format("业务[{0}]远程下载完成,现在要进行导入吗？", row.BizNo), "操作提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                DialogResult = System.Windows.Forms.DialogResult.OK;
                ImagePath = startPath;
                Close();
            }
        }

        private void unzipProgress(object sender, Ionic.Zip.ExtractProgressEventArgs e)
        {
            if (dlprogress.Value < e.EntriesExtracted)
            {
                dlprogress.Value = e.EntriesExtracted;

                Application.DoEvents();
            }
        }

        public string ImagePath { get; set; }

    }


    /// <summary>
    /// 在线业务
    /// </summary>
    class OnlineDataRow
    {
        /// <summary>
        /// 业务序号
        /// </summary>
        public decimal BizId { get; set; }
        /// <summary>
        /// 当前用户
        /// </summary>
        public string UserName { get; set; }
        /// <summary>
        /// 接收时间
        /// </summary>
        public DateTime ReceiveTime { get; set; }
        /// <summary>
        /// 步骤名称
        /// </summary>
        public string StepName { get; set; }
        /// <summary>
        /// 业务编号
        /// </summary>
        public string BizNo { get; set; }
    }

    class OnlineRegistInfo
    {
        /// <summary>
        /// 来源区县
        /// </summary>
        public decimal FromDivisionId { get; set; }
        /// <summary>
        /// 来源业务编号
        /// </summary>
        public decimal FromBizId { get; set; }
    }

    class EasyUIResultInfo<T>
    {
        /// <summary>
        /// 数据行
        /// </summary>
        public IEnumerable<T> rows { get; set; }
        /// <summary>
        /// 是否成功
        /// </summary>
        public bool success { get; set; }
        /// <summary>
        /// 总行数
        /// </summary>
        public int total { get; set; }
        /// <summary>
        /// 错误消息
        /// </summary>
        public string message { get; set; }

        /// <summary>
        /// 附加数据
        /// </summary>
        public object data { get; set; }
    }


}
